<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <style type="text/css">
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
        }

        #allmap {
            width: 100%;
            height: 75%;
            overflow: hidden;
        }

        #r-result {
            width: 380px;
            height: 30px;
            margin: 20px;
            float: left;
        }

        div#ranges {
            width: 500px;
            height: 40px;
            float: left;
            margin: 15px;
        }

        dl,
        dt,
        dd,
        ul,
        li {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        p {
            font-size: 12px;
        }

        dt {
            font-size: 14px;
            font-family: "微软雅黑",serif;
            font-weight: bold;
            border-bottom: 1px dotted #000;
            padding: 5px 0 5px 5px;
            margin: 5px 0;
        }

        dd {
            padding: 5px 0 0 5px;
        }

        li {
            line-height: 28px;
        }

        button#confirmAddress {
            width: 100px;
            height: 40px;
            margin-right: 20px;
            border-radius: 6%;
            background: rgb(13, 155, 242);
            border: none;
            color: white;
            cursor: pointer;
        }

        button#search {
            width: 60px;
            height: 36px;
            line-height: 25px;
            border: none;
            margin-left: -5px;
            background: rgb(224, 224, 224);
            cursor: pointer;
        }

        div#title {
            width: 100%;
            font-size: 20px;
            margin-top: 10px;
            margin-left: 10px;
        }

        div.range {
            width: 50px;
            height: 40px;
            float: left;
            text-align: center;
            line-height: 40px;
            background: rgb(224, 224, 224);
            border-radius: 6%;
            margin-left: 2px;
            cursor: pointer;
        }
    </style>

    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=F0i6SrLmHquLVNLCqpExxPrj8mWVdFwx"></script>
   <!-- <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=VfNxG9fgwm9zWWgsNqbyMoIBTewprG0K"></script>-->
    <!--加载鼠标绘制工具-->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css"/>
    <!--加载检索信息窗口-->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>

    <link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css"/>
    <title>配送范围查询</title>
</head>

<body>
<div id="title">配送范围查询</div>
<div id="r-result">
    <input type="text" id="suggestId" size="20" placeholder="请输入配送的地址" style="width: 300px;height: 30px;"/>
    <button id="search">搜索</button>
</div>
<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
<div id="ranges"></div>
<button id="confirmAddress">确认地址</button>
<i id="text"></i>
<div id="allmap" style="overflow:hidden;zoom:1;position:relative;">
    <div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;">
    </div>
</div>

<div id="resultShape"></div>

<script src="../../lib/jquery-3.3.1.min.js"></script>
<script>
    var ScopeName = [];//生成数组用于保存范围的名字
    var btnColor = [];//用于存储颜色
    //生成范围名字按钮
    $(function () {
        $.ajax({
            url: "/num",
            type: "post",
            dataType: "json",
            success: function (data) {
                $.each(data, function (k, v) {
                    $("div#ranges").append($("<div class='range'>" + v.mapName + "</div>"))
                    ScopeName[k] = v.mapName
                    btnColor[k] = v.mapColor;
                })
                //点击按钮获取区域名
                $("div.range").on("click", function () {
                    var value = null
                    //点击确认按钮把区域名和收货地址传给servlet
                    $("button#confirmAddress").on("click", function () {
                        console.log("---" + value)
                        console.log("===" + $("input#suggestId").val())
                        //给servle传入域名名和收货地址
                        $.ajax({
                            url: "/sendAddress",
                            data: {
                                "Address": $("input#suggestId").val(),
                                "Scope": value
                            },
                            type: "post",
                            dataType: "json",
                            success: function (data) {
                                console.log(data)
                                if (data.flag==="SUCCESS"){
                                    alert("保存地址成功")
                                } else {
                                    alert("保存地址失败")
                                }
                            },
                            error: function (e) {
                                console.log(e)
                            }
                        })
                    })
                    //设置按钮的背景
                    $(this).css("background", btnColor[$(this).index()]);
                    value = $(this).text();
                })
                getMap();
            },
            error: function (e) {
                console.log(e)
            }
        })
    })

    var pointXY = [];//声明数组用户存储经纬度
    var color = null;//用于颜色中转
    //点击区域名字获取范围
    function getMap() {
        $("div.range").on("click", function () {
            var mName = $(this).text()
            $.ajax({
                url: "/map",
                data: {"MapName": mName},
                type: "post",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (k, v) {
                        if (mName === v.mapName) {
                            var a = v.coordinate.split(',');
                            pointXY[k] = new BMap.Point(parseFloat(a[0]), parseFloat(a[1]));
                            color = v.mapColor;
                        }
                    })
                    createScope(pointXY, color)
                },
                error: function (e) {
                    console.log(e)
                }
            })
        })
        var Areas = [];//用于存储全部坐标
        //循环把后端得到的范围名字再传给后端进行寻找对应的经纬度
        var Xy = [];//声明数组用于保存经纬度
        var mc = "";//用于颜色的中转
        var step = 0
        for (var i = 0; i < ScopeName.length; i++) {
            step = i;
            $.ajax({
                url: "/show",
                traditional: true,
                data: {"mName": ScopeName[i]},
                type: "post",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (k, v) {
                        var a = v.coordinate.split(',');
                        Xy[k] = new BMap.Point(parseFloat(a[0]), parseFloat(a[1]));
                        mc = v.mapColor;
                    })
                    createScope(Xy, mc);
                },
                error: function (e) {
                    console.log(e)
                }
            })
        }
        //获取全部坐标
        $.ajax({
            url: "/selectAll",
            type: "post",
            dataType: "json",
            success: function (data) {
                $.each(data, function (k, v) {
                    var a = v.coordinate.split(',');
                    Areas[k] = new BMap.Point(parseFloat(a[0]), parseFloat(a[1]));
                })
                createAllScope(Areas)
            },
            error: function (e) {
                console.log(e)
            }
        })
        //点击查看用户地址是否在配送范围之外
        $("button#search").on("click", function () {
            var result = BMapLib.GeoUtils.isPointInPolygon(posi, createAllScope(Areas));
            if (result == true) {
                $("i#text").css("color", "green").html("在配送区域内");
            } else {
                $("i#text").css("color", "red").html("在配送区域外");
            }
        })

        //生成范围
        function createScope(point, color) {
            var polygon = new BMap.Polygon(point, {
                strokeWeight: 2,
                strokeOpacity: 0,
                fillOpacity: 0.5,
                fillColor: color
            });  //创建多边形
            map.addOverlay(polygon);   //增加多边形
            return polygon;
        }

        //生成全部坐标的范围
        function createAllScope(point) {
            var polygon = new BMap.Polygon(Areas, {strokeWeight: 2, strokeOpacity: 0.1, fillOpacity: 0.1});  //创建多边形
            map.addOverlay(polygon);   //增加多边形
            return polygon;
        }

    }

</script>
<script type="text/javascript">
    // 百度地图API功能
    var posi = null;
    var map = new BMap.Map("allmap");    // 创建Map实例
    var point = new BMap.Point(104.050528,30.556761);
    map.setCurrentCity("成都");          // 设置地图显示的城市 此项是必须设置的
    map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
    map.centerAndZoom(point, 18);
    var marker = new BMap.Marker(point);  // 创建标注
    map.addOverlay(marker);               // 将标注添加到地图中
    marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    function G(id) {
        return document.getElementById(id);
    }

    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
        {
            "input": "suggestId"
            , "location": map
        });

    ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
        var str = "";
        var _value = e.fromitem.value;
        var value = "";
        if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

        value = "";
        if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        G("searchResultPanel").innerHTML = str;
    });

    var myValue;
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        setPlace();
    });

    function setPlace() {
        // map.clearOverlays();    //清除地图上所有覆盖物
        function myFun() {
            var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 18);
            map.addOverlay(new BMap.Marker(pp));    //添加标
            posi = pp;
        }

        var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
        });
        local.search(myValue);

    }
</script>
</body>

</html>